package com.example.light.system.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.light.system.common.Result;
import com.example.light.system.dto.*;
import com.example.light.system.entity.*;
import com.example.light.system.mapper.*;
import com.example.light.system.service.impl.IDeviceService;
import com.example.light.system.service.impl.ISystemLogService;
import com.example.light.system.vo.controlParams;
import com.example.light.system.vo.insertDevice;
import com.example.light.system.vo.insertMode;
import com.example.light.system.vo.searchDevice;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Service
public class deviceService extends ServiceImpl<DeviceMapper, device> implements IDeviceService {
    @Resource
    RoomMapper roomMapper;
    @Resource
    DeviceMapper deviceMapper;
    @Resource
    DeviceTypeMapper deviceTypeMapper;
    @Resource
    RoomDeviceMapper roomDeviceMapper;
    @Resource
    EnvironmentMapper environmentMapper;
    @Resource
    DurationMapper durationMapper;
    @Resource
    ModeMapper modeMapper;
    @Resource
    DeviceModeMapper  deviceModeMapper;
    @Resource
    webSocketService webSocketService;
    @Resource
    ISystemLogService iSystemLogService;

    @Resource
    DeviceEnvironmentMapper deviceEnvironmentMapper;


    /**
     * 获取所有教室信息
     * @return
     */
    public Result<List<room>> getAllRoom(){
        List<room> roomList = roomMapper.selectList(null);
        return Result.success(roomList);
    }

    /**
     * 获取设备类型
     * @return
     */
    public Result<List<deviceType>> getDeviceType(){
        List<deviceType> deviceTypeList = deviceTypeMapper.selectList(null);
        return Result.success(deviceTypeList);
    }

    /**
     * 获取所有设备信息
     * @return
     */
    public Result<ArrayList<allDeviceList>> getAllDevice(){
        // 查询出所有的设备信息
        List<device> deviceList = deviceMapper.selectList(null);
        // 创建数组对象存放最终结果
        ArrayList<allDeviceList> arrayList = new ArrayList<>();
        // 如果当前系统中存在设备，则进行遍历查询归属
        if (deviceList.size() != 0){
            Iterator<device> iterator = deviceList.iterator();
            while (iterator.hasNext()){
                allDeviceList allDeviceList = new allDeviceList();
                device next = iterator.next();
                String roomName = deviceMapper.searchRoomName(next.getDeviceId());
                allDeviceList.setDeviceNumber(next.getDeviceNumber());
                allDeviceList.setDeviceName(next.getDeviceName());
                allDeviceList.setDeviceType(next.getDeviceType());
                allDeviceList.setDeviceMac(next.getDeviceMac());
                allDeviceList.setRoomName(roomName);
                allDeviceList.setDeviceWorkStatus(next.getDeviceWorkStatus());
                allDeviceList.setDeviceOnlineTime(next.getDeviceOnlineTime());
                allDeviceList.setDeviceStatus(next.getDeviceStatus());
                if (next.getDeviceNote() == null || next.getDeviceNote().length() == 0){
                    allDeviceList.setDeviceNote("暂无备注");
                }else {
                    allDeviceList.setDeviceNote(next.getDeviceNote());
                }
                allDeviceList.setDeviceLongitude(next.getDeviceLongitude());
                allDeviceList.setDeviceLatitude(next.getDeviceLatitude());
                arrayList.add(allDeviceList);
            }
        }else {

        }
        return Result.success(arrayList);
    }

    /**
     * 查询设备信息
     *
     * @param searchDevice
     * @return
     */
    public Result<ArrayList> searchDevice(searchDevice searchDevice){
        if (searchDevice.getRoomName() == null || searchDevice.getDeviceName().length() == 5){
            ArrayList list = deviceMapper.searchDevice(null, searchDevice.getDeviceName());
            return Result.success(list);
        }else {
            ArrayList list = deviceMapper.searchDevice(searchDevice.getRoomName(), null);
            return Result.success(list);
        }
    }

    /**
     * 添加新设备
     * @param insertDevice
     * @return
     */
    public Result<String> addDevice(insertDevice insertDevice){
        // 判断设备编号是否重复
        QueryWrapper<device> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("device_number",insertDevice.getDeviceNumber());
        List<device> deviceList = deviceMapper.selectList(objectQueryWrapper);
        // 设备新增标志位与新增映射标志位
        Integer insertMapper = null;
        Integer insert = null;
        // 账号重复则报错
        if (deviceList.size() != 0){
            return Result.fail("编号重复");
        }else {
            // 实例化device对象获取新增设备数据
            device device = new device();
            device.setDeviceNumber(insertDevice.getDeviceNumber());
            device.setDeviceName(insertDevice.getDeviceName());
            device.setDeviceType(insertDevice.getDeviceType());
            device.setDeviceMac(insertDevice.getDeviceMac());
            device.setDeviceStatus(Integer.parseInt(insertDevice.getDeviceStatus()));
            if (insertDevice.getDeviceNote() != null || insertDevice.getDeviceNote().length() != 0) {
                device.setDeviceNote(insertDevice.getDeviceNote());
            }
            device.setDeviceWorkStatus(0);
            // 添加经纬度
            device.setDeviceLongitude(insertDevice.getDeviceLongitude());
            device.setDeviceLatitude(insertDevice.getDeviceLatitude());
            // 新增设备
            insert = deviceMapper.insert(device);
            // 如果成功，则添加教室与设备映射,设备与模式映射
            if (insert == 1){
                // 查询房间id
                String roomNumber = insertDevice.getRoomNumber();
                QueryWrapper<room> wrapper = new QueryWrapper<>();
                wrapper.eq("room_number",roomNumber);
                room room = roomMapper.selectOne(wrapper);
                // 查询设备id
                QueryWrapper<device> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("device_number",insertDevice.getDeviceNumber());
                device selectDevice = deviceMapper.selectOne(queryWrapper);
                // 添加房间与设备映射
                roomDevice roomDevice = new roomDevice();
                roomDevice.setRoomId(room.getRoomId());
                roomDevice.setDeviceId(selectDevice.getDeviceId());
                insertMapper = roomDeviceMapper.insert(roomDevice);
                // 为设备默认添加自定义模式并启用
                deviceMode deviceMode = new deviceMode();
                deviceMode.setDeviceId(selectDevice.getDeviceId());
                deviceMode.setModeId(3);
                deviceMode.setModeStatus(1);
                deviceModeMapper.insert(deviceMode);
                // 实例化新增设备结构体，并存入新增信息
                addDeviceCloud addDeviceCloud = new addDeviceCloud();
                addDeviceCloud.setProduct_id("7z05eNj643");
                addDeviceCloud.setDevice_name(insertDevice.getDeviceName());
                // 向云平台发起新增设备请求
                String url = "https://iot-api.heclouds.com/device/create";
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.set("authorization", "version=2022-05-01&res=userid%2F288125&et=1963297358&method=md5&sign=FcxCXia7emKuYM%2BPqbrppg%3D%3D"); // 添加authorization token
                HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(addDeviceCloud), headers);
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            }else {
                return Result.fail("添加失败");
            }
        }
        // WebSocket推送新数据
        sendDevice();
        return insert==1 && insertMapper == 1?Result.success("添加成功"):Result.fail("添加失败");
    }

    /**
     * 编辑设备信息
     * @param insertDevice
     * @return
     */
    public Result<String> editDevice(insertDevice insertDevice){
        // 查找设备id
        QueryWrapper<device> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("device_number",insertDevice.getDeviceNumber());
        device deviceByNumber = deviceMapper.selectOne(objectQueryWrapper);
        Integer deviceId = deviceByNumber.getDeviceId();
        // 实例化device对象获取新增设备数据
        device deviceTwo = new device();
        deviceTwo.setDeviceId(deviceId);
        deviceTwo.setDeviceName(insertDevice.getDeviceName());
        deviceTwo.setDeviceType(insertDevice.getDeviceType());
        deviceTwo.setDeviceStatus(Integer.parseInt(insertDevice.getDeviceStatus()));
        if (insertDevice.getDeviceNote() != null || insertDevice.getDeviceNote().length() != 0) {
            deviceTwo.setDeviceNote(insertDevice.getDeviceNote());
        }
        deviceTwo.setDeviceWorkStatus(0);
        // 编辑经纬度
        deviceTwo.setDeviceLongitude(insertDevice.getDeviceLongitude());
        deviceTwo.setDeviceLatitude(insertDevice.getDeviceLatitude());
        // 更新设备信息
        int update = deviceMapper.updateById(deviceTwo);
        if (insertDevice.getRoomNumber() != null && insertDevice.getRoomNumber().length() != 0){
            // 查找需要添加映射关系的教室ID
            QueryWrapper<room> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("room_number", insertDevice.getRoomNumber());
            room room = roomMapper.selectOne(queryWrapper);
            Integer roomId = room.getRoomId();
            // 通过deviceId删除原有映射关系
            QueryWrapper<roomDevice> wrapper = new QueryWrapper<>();
            wrapper.eq("device_id", deviceId);
            int delete = roomDeviceMapper.delete(wrapper);
            // 添加新映射关系
            roomDevice roomDevice = new roomDevice();
            roomDevice.setDeviceId(deviceId);
            roomDevice.setRoomId(roomId);
            int inserted = roomDeviceMapper.insert(roomDevice);
            // WebSocket推送新数据
            sendDevice();
            return delete != 0 && inserted != 0?Result.success("保存成功"):Result.fail("保存失败");
        }else {
            // WebSocket推送新数据
            sendDevice();
            return update == 1?Result.success("保存成功"):Result.fail("保存失败");
        }
    }

    /**
     * 删除设备
     * @param deviceNumber
     * @return
     */
    public Result<String> deleteDevice(String deviceNumber){
        // 查找当前设备信息
        QueryWrapper<device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_number", deviceNumber);
        device device = deviceMapper.selectOne(queryWrapper);
        // 删除设备信息
        int delete = deviceMapper.delete(queryWrapper);
        if (delete == 1){
            // 删除设备教室映射
            QueryWrapper<roomDevice> wrapper = new QueryWrapper<>();
            wrapper.eq("device_id", device.getDeviceId());
            int deleteMapper = roomDeviceMapper.delete(wrapper);
            // 删除设备和环境数据映射
            QueryWrapper<deviceEnvironment> WrapperDeviceEnvironment = new QueryWrapper<>();
            WrapperDeviceEnvironment.eq("device_id", device.getDeviceId());
            deviceEnvironmentMapper.delete(WrapperDeviceEnvironment);
            // 删除设备统计时长
            QueryWrapper<duration> wrapperDuration = new QueryWrapper<>();
            wrapper.eq("device_number",device.getDeviceNumber());
            durationMapper.delete(wrapperDuration);
            // 删除设备和灯光模式映射
            QueryWrapper<deviceMode> objectQueryWrapper = new QueryWrapper<>();
            objectQueryWrapper.eq("device_id", device.getDeviceId());
            deviceModeMapper.delete(objectQueryWrapper);
            // 实例化删除设备结构体，并存入新增信息
            deleteDeviceCloud deleteDeviceCloud = new deleteDeviceCloud();
            deleteDeviceCloud.setProduct_id("7z05eNj643");
            deleteDeviceCloud.setDevice_name(device.getDeviceName());
            // 向云平台发起新增设备请求
            String url = "https://iot-api.heclouds.com/device/delete";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("authorization", "version=2022-05-01&res=userid%2F288125&et=1963297358&method=md5&sign=FcxCXia7emKuYM%2BPqbrppg%3D%3D"); // 添加authorization token
            HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(deleteDeviceCloud), headers);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            // WebSocket推送新数据
            sendDevice();
            return deleteMapper == 1?Result.success("删除成功"):Result.fail("删除失败");
        }
        else {
            return Result.fail("删除失败");
        }
    }

    /**
     * 获取房间设备绑定信息
     * @return
     */
    public Result<ArrayList<roomTree>> getDeviceTree(){
        // 获取所有教室信息
        List<room> roomList = roomMapper.selectList(null);
        if (roomList.size() == 0){
            return Result.fail("暂无教室信息");
        }
        // 存放所有教室的roomNumber和roomName信息
        ArrayList<roomTree> roomTreeList = new ArrayList<>();
        Iterator<room> iterator = roomList.iterator();
        while (iterator.hasNext()){
            room next = iterator.next();
            roomTree roomTree = new roomTree();
            roomTree.setRoomNumber(next.getRoomNumber());
            roomTree.setRoomName(next.getRoomName());
            roomTreeList.add(roomTree);
        }
        // 通过room_number查找每个教室所绑定的灯光设备信息并完成添加
        ArrayList<roomTree> arrayList = new ArrayList<>();
        Iterator<roomTree> treeIterator = roomTreeList.iterator();
        while (treeIterator.hasNext()){
            roomTree next = treeIterator.next();
            String roomNumber = next.getRoomNumber();
            ArrayList<deviceTree> deviceTreeList = deviceMapper.searchDeviceByRoomNumber(roomNumber);
            next.setDeviceChild(deviceTreeList);
            arrayList.add(next);
        }
        return Result.success(arrayList);
    }

    /**
     * 获取不同工作状态的设备数量
     * @return
     */
    public Result<deviceWorkStatusInfo> getDeviceWorkStatus(){
        deviceWorkStatusInfo workStatusInfo = new deviceWorkStatusInfo();
        // 查询在线的设备数量
        QueryWrapper<device> onLineWrapper = new QueryWrapper<>();
        onLineWrapper.eq("device_status", 1);
        List<device> onLineDevices = deviceMapper.selectList(onLineWrapper);
        workStatusInfo.setOnLine(onLineDevices.size());
        // 查询离线状态的设备数量
        QueryWrapper<device> offLineWrapper = new QueryWrapper<>();
        offLineWrapper.eq("device_status", 0);
        List<device> offLineDevices = deviceMapper.selectList(offLineWrapper);
        workStatusInfo.setOffLine(offLineDevices.size());
        // 查询异常状态的设备数量
        QueryWrapper<device> exceptionWrapper = new QueryWrapper<>();
        exceptionWrapper.eq("device_status", 2);
        List<device> exceptDevices = deviceMapper.selectList(exceptionWrapper);
        workStatusInfo.setException(exceptDevices.size());
        return Result.success(workStatusInfo);
    }

    // 获取灯光设备开启的数量
    public Result<String> getOnlineDevice(){
        // 灯光设备开光状态发生改变时查询开启的灯光设备
        QueryWrapper<device> onLineWrapper = new QueryWrapper<>();
        onLineWrapper.eq("device_work_status", 1);
        List<device> onLineDevices = deviceMapper.selectList(onLineWrapper);
        onLineDevice onLineDevice = new onLineDevice();
        onLineDevice.setOnLineDeviceCount(onLineDevices.size());
        LocalDateTime now = LocalDateTime.now();
        onLineDevice.setDeviceOnlineTime(now);
        sendOnlineDevice(onLineDevice);
        return Result.success("在线设备查询成功");
    }

    /**
     * 统计设备在线时长
     *
     * @return
     */
    public Result<String> getLightOnlineTimeCount(String deviceNumber){
        // 当设备工作状态被置为0或3时，触发该方法获取设备最近开启时间
        // 获取所关闭设备编号并获取所有设备编号并获取计算在线时长并计入在线时长统计表中
        ArrayList<duration> arrayList = new ArrayList<>();
        QueryWrapper<device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_number", deviceNumber);
        List<device> deviceList = deviceMapper.selectList(queryWrapper);
        // 如果存在设备则遍历设备获取设备最近上线时间并计算在线时长
        if (deviceList.size() != 0){
            Iterator<device> iterator = deviceList.iterator();
            while (iterator.hasNext()){
                device next = iterator.next();
                // 获取最近一次开启时间和当前时间
                String deviceOnlineTime = next.getDeviceOnlineTime().toString().replace("T"," ");
                LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);;
                String nowTime = now.toString().replace("T", " ");
                // 计算时长
                DateTime data1 = DateUtil.parse(deviceOnlineTime);
                DateTime data2 = DateUtil.parse(nowTime);
                long minutes = DateUtil.between(data1, data2, DateUnit.MINUTE);
                BigDecimal bigDecimal = new BigDecimal(minutes);
                int durationCount = bigDecimal.intValue();
                // 查询数据库中是否存在该设备的时长统计记录
                QueryWrapper<duration> wrapper = new QueryWrapper<>();
                wrapper.eq("device_number",next.getDeviceNumber());
                duration durationSelect = durationMapper.selectOne(wrapper);
                // 如果有，则相加统计总和并修改
                // 如果没有，则新增
                if (durationSelect == null){
                    duration duration = new duration();
                    duration.setDeviceNumber(next.getDeviceNumber());
                    duration.setDeviceName(next.getDeviceName());
                    duration.setDeviceOnline(durationCount);
                    duration.setDurationTime(now);
                    durationMapper.insert(duration);
                }else {
                    // 累计时长
                    durationCount = durationCount + durationSelect.getDeviceOnline();
                    // 更新数据
                    UpdateWrapper<duration> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", durationSelect.getId());
                    duration duration = new duration();
                    duration.setDeviceNumber(durationSelect.getDeviceNumber());
                    duration.setDeviceName(durationSelect.getDeviceName());
                    duration.setDeviceOnline(durationCount);
                    duration.setDurationTime(now);
                    durationMapper.update(duration,updateWrapper);
                }
            }
            getUsedCount();
            return Result.success("使用时长获取成功");
        }else {
            return Result.fail("当前无设备接入");
        }
    }

    /**
     * 初始化获取设备使用时长信息
     *
     * @return
     */
    public Result<String> getUsedCount(){
        ArrayList<duration> arrayList = new ArrayList<>();
        List<duration> durationList = durationMapper.selectList(null);
        Iterator<duration> iterator = durationList.iterator();
        while (iterator.hasNext()){
            duration next = iterator.next();
            arrayList.add(next);
        }
        sendOlineDuration(arrayList);
        return Result.success("时长信息返回成功");
    }

    // 获取环境数据
    public Result<String> getEnvironmentData(JSONObject subData){
        // 通过名称查找设备是否存在
        // 获取设备名称
        String deviceName = subData.get("deviceName").toString();
        JSONObject environmentDataJson = subData.getJSONObject("params");
//        System.out.println("环境数据"+environmentDataJson);
        // 获取温度数据
        JSONObject temperatureJson = environmentDataJson.getJSONObject("Temperature");
        float temperature = Float.parseFloat(temperatureJson.get("value").toString());
        // 获取湿度数据
        JSONObject humidityJson = environmentDataJson.getJSONObject("Humidity");
        float humidity = Float.parseFloat(humidityJson.get("value").toString());
        // 亮度
        JSONObject luminanceJson = environmentDataJson.getJSONObject("Luminance");
        Integer luminance = Integer.parseInt(luminanceJson.get("value").toString());
        // 火焰
        JSONObject fireJson = environmentDataJson.getJSONObject("Fire");
        Integer fire = Boolean.valueOf(fireJson.get("value").toString())?1:0;
        // 烟雾浓度
        JSONObject smokeJson = environmentDataJson.getJSONObject("Smoke");
        Integer smoke = Integer.parseInt(smokeJson.get("value").toString());
        QueryWrapper<device> wrapper = new QueryWrapper<>();
        wrapper.eq("device_name",deviceName);
        device device = deviceMapper.selectOne(wrapper);
        // 获取deviceId查找色温值
        QueryWrapper<deviceMode> queryWrapperMode = new QueryWrapper<>();
        queryWrapperMode.eq("device_id",device.getDeviceId());
        deviceMode deviceMode = deviceModeMapper.selectOne(queryWrapperMode);
        Integer modeId = deviceMode.getModeId();
        mode mode = modeMapper.selectById(modeId);
        Integer preColorTemperature = mode.getPreColorTemperature();
        String deviceNumber = "";
        if (device != null){
            // 存在，则获取设备编号
            deviceNumber = device.getDeviceNumber();
            // 将设备编号存入返回的数据中
        }else{
            // 设备不存在则发布通知，提示设备不存在，要求确认来源并完成设备添加后才能接收数据
            iSystemLogService.addAnnouncement(deviceName, 0);
            return Result.fail("异常数据");
        }
        environment environment = new environment();
        //随机生成一个UUID对象
        String uuid = UUID.randomUUID().toString();
        environment.setEnvironmentUuid(uuid);
        Random random = new Random();
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        environment.setEnvironmentTime(now);
        environment.setEnvironmentFire(0);
        // 亮度
        environment.setEnvironmentLuminance(luminance);
        // 随机色温（1000-9999）
        environment.setEnvironmentColortemperature(random.nextInt(40)+(preColorTemperature - 20));
        // 温度
        environment.setEnvironmentTemperature(temperature);
        // 湿度
        environment.setEnvironmentHumidity(humidity);
        // 烟雾浓度
        environment.setEnvironmentSmokescope(smoke);
        // 火焰
        environment.setEnvironmentFire(fire);
        int insert = environmentMapper.insert(environment);
        // 添加环境数据与设备映射
        QueryWrapper<environment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("environment_uuid",uuid);
        environment selectEnvironment = environmentMapper.selectOne(queryWrapper);
        deviceEnvironment deviceEnvironment = new deviceEnvironment();
        deviceEnvironment.setEnvironmentId(selectEnvironment.getId());
        deviceEnvironment.setDeviceId(device.getDeviceId());
        deviceEnvironmentMapper.insert(deviceEnvironment);
        // 计算该检测点安全系数
        // 温度、湿度、烟雾浓度的最小和最大值
        double temperatureMin = 0.0, temperatureMax = 50.0;
        double humidityMin = 20.0, humidityMax = 90.0;
        double smokeScopeMin = 0.0, smokeScopeMax = 100.0;
        // 权重
        double weightTemperature = 0.3;
        double weightHumidity = 0.2;
        double weightSmokeScope = 0.5;
        // 归一化计算
        double temperatureNormalization = (environment.getEnvironmentTemperature() - temperatureMin) / (temperatureMax - temperatureMin);
        double humidityNormalization = (environment.getEnvironmentHumidity() - humidityMin) / (humidityMax - humidityMin);
        double smokeScopeNormalization = (environment.getEnvironmentSmokescope() - smokeScopeMin) / (smokeScopeMax - smokeScopeMin);
        // 综合风险评估值securityLevel
        Integer securityLevel;
        if (fire == 1){
            securityLevel = 100;
        }else {
            securityLevel = (int) (((temperatureNormalization * weightTemperature) + (humidityNormalization * weightHumidity) + (smokeScopeNormalization * weightSmokeScope))*100);
        }
        if (insert != 0){
            onlineEnvironment onlineEnvironment = new onlineEnvironment();
            onlineEnvironment.setEnvironmentLuminance(environment.getEnvironmentLuminance());
            onlineEnvironment.setEnvironmentColortemperature(environment.getEnvironmentColortemperature());
            onlineEnvironment.setEnvironmentTemperature(environment.getEnvironmentTemperature());
            onlineEnvironment.setEnvironmentHumidity(environment.getEnvironmentHumidity());
            onlineEnvironment.setEnvironmentSmokescope(environment.getEnvironmentSmokescope());
            onlineEnvironment.setEnvironmentFire(environment.getEnvironmentFire());
            onlineEnvironment.setDeviceWorkStatus(device.getDeviceWorkStatus());
            onlineEnvironment.setEnvironmentTime(now);
            onlineEnvironment.setSecurityLevel(securityLevel);
            sendEnvironment(deviceNumber, onlineEnvironment);
            return Result.success("数据采集成功");
        }else {
            return Result.fail("数据采集失败");
        }
    }

    /**
     * 改变设备状态，并将上线消息发送到通知栏
     * @param subData
     * @param status
     */
    public void changeDeviceStatus(JSONObject subData,Integer status){
        // 获取设备名称
        String deviceName = subData.get("deviceName").toString();
        // 根据设备名称更改设备状态
        UpdateWrapper<device> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("device_name", deviceName);
        if (status == 1){
            // 更改设备为启用状态
            device device = new device();
            device.setDeviceStatus(1);
            deviceMapper.update(device, updateWrapper);
            iSystemLogService.addAnnouncement(deviceName, 1);
        } else if (status == 0) {
            // 更改设备为离线状态
            device device = new device();
            device.setDeviceStatus(0);
            deviceMapper.update(device, updateWrapper);
            iSystemLogService.addAnnouncement(deviceName, 2);
        }
    }

    /**
     * 新增灯光模式
     *
     * @param insertMode
     * @return
     */
    public Result<Integer> addLightMode(insertMode insertMode){
        // 判断数据是否为空
        if (insertMode.getModeName() == null || insertMode.getModeName() == "" || insertMode.getPreLuminance() == 0 || insertMode.getPreColorTemperature() == 0){
            return Result.fail("自定义模式添加失败");
        }else {
            //随机生成一个UUID对象
            String uuid = UUID.randomUUID().toString();
            // 获取新增模式数据
            mode mode = new mode();
            mode.setModeName(insertMode.getModeName());
            mode.setPreLuminance(insertMode.getPreLuminance());
            mode.setPreColorTemperature(insertMode.getPreColorTemperature());
            mode.setModeUuid(uuid);
            mode.setIsSystem(0);
            // 新增模式
            int insert = modeMapper.insert(mode);
            if (insert == 0){
                return Result.fail("自定义模式添加失败");
            }else {
                QueryWrapper<mode> wrapper = new QueryWrapper<>();
                wrapper.eq("mode_uuid", uuid);
                mode selectMode = modeMapper.selectOne(wrapper);
                Integer modeId = mode.getId();
                return Result.success("自定义模式添加成功",modeId);
            }
        }
    }
    // 返回所有系统灯光模式
    public Result<List<mode>> getSystemLightMode(){
        QueryWrapper<mode> wrapper = new QueryWrapper<>();
        wrapper.eq("is_system", 1);
        List<mode> modeList = modeMapper.selectList(wrapper);
        if (modeList.size() == 0){
            return Result.fail("无系统模式");
        }else {
            return Result.success(modeList);
        }
    }

    // 返回所有自定义灯光模式
    public Result<List<mode>> getAutoLightMode(){
        QueryWrapper<mode> wrapper = new QueryWrapper<>();
        wrapper.eq("is_system", 0);
        List<mode> modeList = modeMapper.selectList(wrapper);
        if (modeList.size() == 0){
            return Result.fail("无自定义模式");
        }else {
            return Result.success(modeList);
        }
    }

    // 查询设备状态
    public Result<device> getDeviceStatus(String deviceNumber){
        if (deviceNumber == null){
            return Result.fail("设备状态查询失败");
        }else {
            QueryWrapper<device> wrapper = new QueryWrapper<>();
            wrapper.eq("device_number", deviceNumber);
            device device = deviceMapper.selectOne(wrapper);
            return Result.success(device);
        }
    }

    // 获取已开启的模式id
    public Result<Integer> getDeviceMode(String deviceNumber){
        // 查询设备id
        QueryWrapper<device> wrapper = new QueryWrapper<>();
        wrapper.eq("device_number", deviceNumber);
        device device = deviceMapper.selectOne(wrapper);
        Integer deviceId = device.getDeviceId();
        QueryWrapper<deviceMode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", deviceId);
        deviceMode deviceMode = deviceModeMapper.selectOne(queryWrapper);
        Integer modeId = deviceMode.getModeId();
        return Result.success(modeId);
    }

    // 更换绑定模式
    public Result<String> changeMode(Integer deviceNumber, Integer modeId){
        // 查找设备id
        QueryWrapper<device> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("device_number", deviceNumber);
        device device = deviceMapper.selectOne(objectQueryWrapper);
        // 解除所有模式绑定
        QueryWrapper<deviceMode> wrapper = new QueryWrapper<>();
        wrapper.eq("device_id", device.getDeviceId());
        deviceModeMapper.delete(wrapper);
        // 新增绑定模式
        deviceMode deviceMode = new deviceMode();
        deviceMode.setDeviceId(device.getDeviceId());
        deviceMode.setModeId(modeId);
        deviceMode.setModeStatus(1);
        deviceModeMapper.insert(deviceMode);
        return Result.success("绑定模式更换成功");
    }

    /**
     * 删除自定义模式
     * @param modeId
     * @return
     */
    public Result<String> deleteMode(Integer modeId){
        // 删除模式
        int i = modeMapper.deleteById(modeId);
        if (i == 0){
            return Result.fail("删除失败");
        }else {
            // 查找是否存在映射关系
            QueryWrapper<deviceMode> wrapper = new QueryWrapper<>();
            wrapper.eq("mode_id", modeId);
            List<deviceMode> deviceModes = deviceModeMapper.selectList(wrapper);
            if (deviceModes.size() == 0){
                return Result.success("删除成功");
            }else {
                int delete = deviceModeMapper.delete(wrapper);
                return delete == 0?Result.fail("删除失败"):Result.success("删除成功");
            }
        }
    }

    /**
     * 控制指令
     * @param controlParams
     * @return
     */
    public Result<String> controlDevice(controlParams controlParams){
        String url = "https://iot-api.heclouds.com/thingmodel/call-service";
        if (controlParams.getDeviceNumberSet().size() > 1)
        {
            // 关闭所有灯光
            List<device> deviceList = deviceMapper.selectList(null);
            Iterator<device> iteratored = deviceList.iterator();
            while (iteratored.hasNext()){
                String next = iteratored.next().getDeviceNumber();
                // 查询设备名称
                QueryWrapper<device> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("device_number", next);
                device device = deviceMapper.selectOne(queryWrapper);
                String offDeviceName = device.getDeviceName();
                // 关闭当前设备灯光（状态改变）
                UpdateWrapper<device> updateDeviceWrapper = new UpdateWrapper<>();
                updateDeviceWrapper.eq("device_id", device.getDeviceId());
                device updateDeviceStatus = new device();
                updateDeviceStatus.setDeviceWorkStatus(0);
                deviceMapper.update(updateDeviceStatus, updateDeviceWrapper);
                // 将控制设备number和控制命令存入指令集
                orderParams orderParamsAll = new orderParams();
                orderParamsAll.setLEDSwitch(0);
                orderSet orderSetAll = new orderSet();
                orderSetAll.setProduct_id("7z05eNj643");
                orderSetAll.setDevice_name(offDeviceName);
                orderSetAll.setIdentifier("LED");
                orderSetAll.setParams(orderParamsAll);
                // 发布控制命令到云平台关闭灯光（物理改变）
                HttpHeaders headersAll = new HttpHeaders();
                headersAll.setContentType(MediaType.APPLICATION_JSON);
                headersAll.set("authorization", "version=2022-05-01&res=userid%2F288125&et=1963297358&method=md5&sign=FcxCXia7emKuYM%2BPqbrppg%3D%3D"); // 添加authorization token
                HttpEntity<String> entityAll = new HttpEntity<>(JSON.toJSONString(orderSetAll), headersAll);
                RestTemplate restTemplateAll = new RestTemplate();
                ResponseEntity<String> responseAll = restTemplateAll.postForEntity(url, entityAll, String.class);
            }
        }
        // 获取设备编号,将对应设备的工作状态置为1
        // 获取设备编号，获取设备名称地址
        // arrayList存储设备名称，便于指令下发至对应终端设备
        ResponseEntity<String> response = null;
        Iterator<String> iterator = controlParams.getDeviceNumberSet().iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            UpdateWrapper<device> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("device_number",next);
            device device = new device();
            // 如果指令为turn_on，则将设备工作状态置为1,并将控制参数传入orderParams
            // 如果指令为turn_off,则将设备工作状态置为0
            orderParams orderParams = new orderParams();
            // 查找设备名称和id
            QueryWrapper<device> wrapper = new QueryWrapper<>();
            wrapper.eq("device_number", next);
            device selectDevice = deviceMapper.selectOne(wrapper);
            String deviceName = selectDevice.getDeviceName();
            Integer deviceId = selectDevice.getDeviceId();
            if ("turn_on".equals(controlParams.getOrder())){
                device.setDeviceWorkStatus(1);
                orderParams.setLEDSwitch(1);
                // 更新设备使用时间
                UpdateWrapper<device> updateWrapper1 = new UpdateWrapper<>();
                device updataDevice = new device();
                LocalDateTime onlineTime = LocalDateTime.now();
                updateWrapper1.eq("device_number",next);
                updataDevice.setDeviceOnlineTime(onlineTime);
                deviceMapper.update(updataDevice,updateWrapper1);
                // 将控制设备number和控制命令存入指令集,先关闭设备灯光
                orderParams orderParamsOne = new orderParams();
                orderParamsOne.setLEDSwitch(0);
                orderSet orderSetOne = new orderSet();
                orderSetOne.setProduct_id("7z05eNj643");
                orderSetOne.setDevice_name(deviceName);
                orderSetOne.setIdentifier("LED");
                orderSetOne.setParams(orderParamsOne);
                // 发布控制命令到云平台关闭灯光（物理改变）
                HttpHeaders headersOne = new HttpHeaders();
                headersOne.setContentType(MediaType.APPLICATION_JSON);
                headersOne.set("authorization", "version=2022-05-01&res=userid%2F288125&et=1963297358&method=md5&sign=FcxCXia7emKuYM%2BPqbrppg%3D%3D"); // 添加authorization token
                HttpEntity<String> entityOne = new HttpEntity<>(JSON.toJSONString(orderSetOne), headersOne);
                RestTemplate restTemplateOne = new RestTemplate();
                ResponseEntity<String> responseOne = restTemplateOne.postForEntity(url, entityOne, String.class);
                // 延时400毫秒，避免请求冲突
                try {
                    Thread.sleep(400);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else if ("turn_off".equals(controlParams.getOrder())){
                device.setDeviceWorkStatus(0);
                orderParams.setLEDSwitch(0);
                // 获取设备使用时长
                getLightOnlineTimeCount(next);
            }
            // 改变设备工作状态
            int update = deviceMapper.update(device, updateWrapper);
            if (update != 0){
                getOnlineDevice();
            }
            // 通过ID查找设备所开启的模式数据
            QueryWrapper<deviceMode> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("device_id",deviceId);
            deviceMode deviceMode = deviceModeMapper.selectOne(queryWrapper);
            Integer modeId = deviceMode.getModeId();
            mode mode = modeMapper.selectById(modeId);
            Integer preLuminance = mode.getPreLuminance();
            Integer preColorTemperature = mode.getPreColorTemperature();
            orderParams.setLEDPreLuminanceValue(preLuminance);
            // 色温转化RGB
            int[] rgb = new int[3];
            double temp = preColorTemperature / 100.0;
            // 红色
            if(temp <= 66) {
                rgb[0] = 255;
            } else {
                double red = temp - 60;
                red = 329.698727446 * Math.pow(red, -0.1332047592);
                rgb[0] = Math.max(0, Math.min(255, (int) red));
            }
            // 绿色
            if(temp <= 66) {
                double green = temp;
                green = 99.4708025861 * Math.log(green) - 161.1195681661;
                rgb[1] = Math.max(0, Math.min(255, (int) green));
            } else {
                double green = temp - 60;
                green = 288.1221695283 * Math.pow(green, -0.0755148492);
                rgb[1] = Math.max(0, Math.min(255, (int) green));
            }
            // 蓝色
            if(temp >= 66) {
                rgb[2] = 255;
            } else if(temp <= 19) {
                rgb[2] = 0;
            } else {
                double blue = temp - 10;
                blue = 138.5177312231 * Math.log(blue) - 305.0447927307;
                rgb[2] = Math.max(0, Math.min(255,(int) blue));
            }
            rgb[0] = (int)((rgb[0] / 255.0) * 1000);
            rgb[1] = (int)((rgb[1] / 255.0) * 1000);
            rgb[2] = (int)((rgb[2] / 255.0) * 1000);
            orderParams.setLEDRed(rgb[0]);
            orderParams.setLEDGreen(rgb[1]);
            orderParams.setLEDBlue(rgb[2]);
            // 将控制设备number和控制命令存入指令集
            orderSet orderSet = new orderSet();
            orderSet.setProduct_id("7z05eNj643");
            orderSet.setDevice_name(deviceName);
            orderSet.setIdentifier("LED");
            orderSet.setParams(orderParams);
            // 发布控制命令到云平台
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("authorization", "version=2022-05-01&res=userid%2F288125&et=1963297358&method=md5&sign=FcxCXia7emKuYM%2BPqbrppg%3D%3D"); // 添加authorization token
            HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(orderSet), headers);
            RestTemplate restTemplate = new RestTemplate();
            response = restTemplate.postForEntity(url, entity, String.class);
        }
        return response.getStatusCode() == HttpStatus.OK?Result.success("Success"):Result.fail("Failed");
    }

    /**
     * 关闭所有灯光设备，规划逃生路线
     * @return
     */
    public Result<String> offLineAllDevice(){
        // 将当前设备所计算出的危险系数以键值对的方式存入map集合
        HashMap<String, Integer> mapSecurityLevel = new HashMap<>();
        // 查询所有设备
        List<device> deviceList = deviceMapper.selectList(null);
        // 遍历所有设备
        Iterator<device> iterator = deviceList.iterator();
        while (iterator.hasNext()){
            device next = iterator.next();
            // 关闭当前设备灯光（状态改变）
            UpdateWrapper<device> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("device_id", next.getDeviceId());
            device device = new device();
            device.setDeviceWorkStatus(0);
            deviceMapper.update(device, updateWrapper);
            // 将控制设备number和控制命令存入指令集
            orderParams orderParams = new orderParams();
            orderParams.setLEDSwitch(0);
            orderSet orderSetAll = new orderSet();
            orderSetAll.setProduct_id("7z05eNj643");
            orderSetAll.setDevice_name(next.getDeviceName());
            orderSetAll.setIdentifier("LED");
            orderSetAll.setParams(orderParams);
            // 发布控制命令到云平台关闭灯光（物理改变）
            String url = "https://iot-api.heclouds.com/thingmodel/call-service";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("authorization", "version=2022-05-01&res=userid%2F288125&et=1963297358&method=md5&sign=FcxCXia7emKuYM%2BPqbrppg%3D%3D"); // 添加authorization token
            HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(orderSetAll), headers);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            // 发布最新环境数据请求到云平台,请求该设备所处环境数据
            String urlGet = "https://iot-api.heclouds.com/thingmodel/query-device-property?product_id=7z05eNj643&device_name="+next.getDeviceName();
            HttpHeaders headersGet = new HttpHeaders();
            headersGet.setContentType(MediaType.APPLICATION_JSON);
            headersGet.set("authorization", "version=2022-05-01&res=userid%2F288125&et=1963297358&method=md5&sign=FcxCXia7emKuYM%2BPqbrppg%3D%3D"); // 添加authorization token
            HttpEntity<String> entityGet = new HttpEntity<>(headersGet);
            RestTemplate restTemplateGet = new RestTemplate();
            ResponseEntity<String> responseGet = restTemplateGet.exchange(urlGet, HttpMethod.GET, entityGet, String.class);
            JSONObject jsonObject = JSON.parseObject(responseGet.getBody());
            JSONArray data = jsonObject.getJSONArray("data");
            Iterator<Object> iteratored = data.iterator();
            Integer Fire=0, Smoke=0;
            float Humidity=0, Temperature=0;
            // 遍历当前设备的当前环境数据
            while (iteratored.hasNext()){
                Object nexted = iteratored.next();
                String jsonString = JSON.toJSONString(nexted);
                JSONObject jsonData = JSON.parseObject(jsonString);
                String identifier = jsonData.get("identifier").toString();
                if ("Fire".equals(identifier)){
                    Fire = Boolean.valueOf(jsonData.get("value").toString())?1:0;
                }
                if ("Humidity".equals(identifier)){
                    Humidity = Float.parseFloat(jsonData.get("value").toString());
                }
                if ("Smoke".equals(identifier)){
                    Smoke = Integer.parseInt(jsonData.get("value").toString());
                }
                if ("Temperature".equals(identifier)){
                    Temperature = Float.parseFloat(jsonData.get("value").toString());
                }
            }
            // 该设备环境数据遍历获取完成，进行安全系数评定
            // 计算该检测点安全系数
            // 温度、湿度、烟雾浓度的最小和最大值
            double temperatureMin = 0.0, temperatureMax = 50.0;
            double humidityMin = 20.0, humidityMax = 90.0;
            double smokeScopeMin = 0.0, smokeScopeMax = 100.0;
            // 权重
            double weightTemperature = 0.3;
            double weightHumidity = 0.2;
            double weightSmokeScope = 0.5;
            // 归一化计算
            double temperatureNormalization = (Temperature - temperatureMin) / (temperatureMax - temperatureMin);
            double humidityNormalization = (Humidity - humidityMin) / (humidityMax - humidityMin);
            double smokeScopeNormalization = (Smoke - smokeScopeMin) / (smokeScopeMax - smokeScopeMin);
            // 综合风险评估值securityLevel(此系数为危险系数，数值越高，危险性越高)
            Integer securityLevel = 0;
            if (Fire == 1){
                securityLevel = 100;
            }else {
                securityLevel = (int) (((temperatureNormalization * weightTemperature) + (humidityNormalization * weightHumidity) + (smokeScopeNormalization * weightSmokeScope))*100);
            }
            mapSecurityLevel.put(next.getDeviceName(), securityLevel);
        }
        // 各点安全系数计算完成，开始计算逃生路线（在理想模型情况下，假设Light001为起点计算，优先考虑危险系数）
        // 获取Light001经纬度
        QueryWrapper<device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_name", "Light001");
        device device = deviceMapper.selectOne(queryWrapper);
        // 起点经度
        Double originLon = device.getDeviceLongitude();
        // 起点维度
        Double originLat = device.getDeviceLatitude();
        // 距离
        double distance = 0;
        HashMap<String, Double> mapPath = new HashMap<>();
        Iterator<device> iteratorPath = deviceList.iterator();
        // 遍历所有节点，利用球面距离公式（Haversine公式）计算起始点两点直线距离
        while (iteratorPath.hasNext()){
            device next = iteratorPath.next();
            // 目标点经度
            Double endLon = next.getDeviceLongitude();
            // 目标点维度
            Double endLat = next.getDeviceLatitude();
            if (!next.getDeviceName().equals(device.getDeviceName())){
                // 计算距离
                final int R = 6371; // 地球半径，单位：公里

                double latDistance = Math.toRadians(endLat - originLat);
                double lonDistance = Math.toRadians(endLon - originLon);
                double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                        + Math.cos(Math.toRadians(originLat)) * Math.cos(Math.toRadians(endLat))
                        * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
                double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                distance = R * c; // 计算出来的距离单位为公里
                mapPath.put(next.getDeviceName(), distance);
            }
        }
        // 存放最终路径权限值
        HashMap<String, Double> mapResult = new HashMap<>();
        // 根据安全系数和距离权重计算
        Iterator<device> deviceIterator = deviceList.iterator();
        while (deviceIterator.hasNext()){
            device next = deviceIterator.next();
            String deviceName = next.getDeviceName();
            if (!"Light001".equals(deviceName)){
                for (Map.Entry entry : mapSecurityLevel.entrySet()){
                    if (deviceName.equals(entry.getKey())){
                        // 获取该点危险系数
                        Integer dangerValue = Integer.parseInt(entry.getValue().toString());
                        for (Map.Entry entryPath : mapPath.entrySet()){
                            if (deviceName.equals(entryPath.getKey())){
                                // 获取距离
                                Double PathValue = Double.valueOf(entry.getValue().toString());
                                // 计算综合权重值
                                // 权重设定
                                double weightDanger = 0.6;
                                double weightDistance = 0.4;
                                // 计算加权值
                                double weightedValue = weightDanger * (dangerValue/100) + weightDistance * (PathValue/7);
                                mapResult.put(deviceName, weightedValue);
                            }
                        }
                    }
                }
            }
        }
        // 比较综合权限值大小
        // 中间比较值
        double midValue = 0;
        String midDeviceName = "";
        // 存放最终路线结果
        ArrayList<String> arrayList = new ArrayList<>();
        for (Map.Entry entry : mapResult.entrySet()){
            if (midValue == 0){
                midValue = Double.valueOf(entry.getValue().toString());
                midDeviceName = entry.getKey().toString();
            }else {
                if (Double.valueOf(entry.getValue().toString()) < midValue){
                    midValue = Double.valueOf(entry.getValue().toString());
                    midDeviceName = entry.getKey().toString();
                }
            }
        }
        arrayList.add("Light001");
        arrayList.add(midDeviceName);
        // 获取到逃生路线，开始下发指令
        Iterator<String> iteratored = arrayList.iterator();
        while (iteratored.hasNext()){
            String next = iteratored.next();
            // 改变状态（软件）
            UpdateWrapper<device> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("device_name", next);
            device deviceUpdate = new device();
            deviceUpdate.setDeviceWorkStatus(1);
            int update = deviceMapper.update(deviceUpdate, updateWrapper);
            // 发起请求开启灯光设备
            orderParams orderParams = new orderParams();
            orderParams.setLEDSwitch(1);
            orderParams.setLEDPreLuminanceValue(2000);
            orderParams.setLEDRed(1000);
            orderParams.setLEDGreen(1000);
            orderParams.setLEDBlue(1000);
            orderSet orderSet = new orderSet();
            orderSet.setProduct_id("7z05eNj643");
            orderSet.setDevice_name(next);
            orderSet.setIdentifier("LED");
            orderSet.setParams(orderParams);
            // 发布控制命令到云平台关闭灯光（物理改变）
            String url = "https://iot-api.heclouds.com/thingmodel/call-service";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("authorization", "version=2022-05-01&res=userid%2F288125&et=1963297358&method=md5&sign=FcxCXia7emKuYM%2BPqbrppg%3D%3D"); // 添加authorization token
            HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(orderSet), headers);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        }
        return Result.success("应急模式已开启！引导路线已规划成功！");
    }

    // WebSocket监听并推送设备数据
    public void sendDevice(){
        Result<ArrayList<allDeviceList>> allDevice = getAllDevice();
        socketOutMessage socketOutMessage = new socketOutMessage();
        socketOutMessage.setDataType("设备数据");
        socketOutMessage.setDataBody(allDevice.getData());
        webSocketService.sendMessage(JSON.toJSONString(socketOutMessage));
    }

    // WebSocket监听并推送环境数据
    public void sendEnvironment(String deviceId, onlineEnvironment onlineEnvironment){
        ArrayList<onlineEnvironment> arrayList = new ArrayList<>();
        arrayList.add(onlineEnvironment);
        socketOutMessage socketOutMessage = new socketOutMessage();
        socketOutMessage.setDataType(deviceId);
        socketOutMessage.setDataBody(arrayList);
        webSocketService.sendMessage(JSON.toJSONString(socketOutMessage));
    }

    // WebSocket监听并推送在线设备数量
    public void sendOnlineDevice(onLineDevice onLineDevice){
        ArrayList<onLineDevice> arrayList = new ArrayList<>();
        arrayList.add(onLineDevice);
        socketOutMessage socketOutMessage = new socketOutMessage();
        socketOutMessage.setDataType("在线设备");
        socketOutMessage.setDataBody(arrayList);
        webSocketService.sendMessage(JSON.toJSONString(socketOutMessage));
    }

    // WebSocket监听并推送设备在线时长
    public void sendOlineDuration(ArrayList<duration> arrayList){
        socketOutMessage socketOutMessage = new socketOutMessage();
        socketOutMessage.setDataType("在线时长");
        socketOutMessage.setDataBody(arrayList);
        webSocketService.sendMessage(JSON.toJSONString(socketOutMessage));
    }
}
